876. 链表的中间结点
为保证权益,题目请参考 876. 链表的中间结点(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL)
{
}
};
class Solution
{
public:
ListNode *middleNode(ListNode *head)
{
if (head == NULL)
{
return NULL;
}
ListNode *p1 = head;
ListNode *p2 = head->next;
while (p2 != NULL)
{
if (p2->next != NULL)
{
if (p2->next->next != NULL)
{
p2 = p2->next->next;
p1 = p1->next;
}
else
{
p1 = p1->next;
break;
}
}
else
{
p1 = p1->next;
break;
}
}
return p1;
}
};
int main()
{
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56